package com.he.algorithm.search;

/**
 * @description: 折半查找(二分查找)，适用于有序数据
 * @Author: HCL
 * @Date: 2024/8/27 9:02
 */
public class HalfSearch {

    public static int binarySearch(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1; // 可选：添加对空数组或null数组的检查
        }
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2; // 防止整数溢出
            System.out.println("high = " + high);
            System.out.println("low = " + low);
            System.out.println("mid = " + mid);
            if (target == nums[mid]) {
                return mid;
            } else if (target > nums[mid]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1; // 目标不在数组中
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 5, 6, 7, 9};
        int res = binarySearch(nums, 3);
        if (res == -1) {
            System.out.println("没有该数据");
        } else {
            System.out.println("位置为：" + res);
        }
    }
}
